using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;

namespace Niu
{
    public delegate void nHotKeyEventHandler(object sender);

    [ToolboxBitmapAttribute(typeof(System.Windows.Forms.HelpProvider))]
    public partial class nHotKey : Component
    {
        public event nHotKeyEventHandler OnHotKey;

        private Keys AllKey = Keys.None;

        [DllImport("user32")]
        private static extern Boolean RegisterHotKey(IntPtr hWnd, Int32 ID, Int32 ComboKey, Keys VirtualKey);

        [DllImport("user32")]
        private static extern Boolean UnregisterHotKey(IntPtr hWnd, Int32 ID);

        private void RaiseHotkey()
        {
            OnHotKey(this);
        }

        private Int32 GetcKey(Keys vKey)
        {
            Int32 cKey = 0;

            if ((vKey & Keys.Alt) != 0)
            {
                cKey += 1; //Alt
            }

            if ((vKey & Keys.Control) != 0)
            {
                cKey += 2; //Contrl
            }

            if ((vKey & Keys.Shift) != 0)
            {
                cKey += 4; //shift
            }

            return cKey;
        }

        private Keys GetvKey(Keys vKey)
        {
            return (vKey & Keys.KeyCode);
        }

        public nHotKey()
        {
            InitializeComponent();
        }

        public nHotKey(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        public Boolean Register()
        {
            m_nHotMsg.OnHotMsg = new nHotMsg.HotMsg(RaiseHotkey);

            return RegisterHotKey(m_nHotMsg.Handle, 0, GetcKey(this.AllKey), GetvKey(this.AllKey));
        }

        public Boolean Register(Keys Key)
        {
            this.AllKey = Key;

            return Register();
        }

        public Boolean UnRegister()
        {
            return UnregisterHotKey(m_nHotMsg.Handle, 0);
        }

        [Category("N_Property"), Description("Get/Set HotKey")]
        public Keys Key
        {
            get
            {
                return this.AllKey;
            }
            set
            {
                this.AllKey = value;
            }
        }


    }
}